﻿using System;
using System.IO;
using System.Xml.Serialization;
using DHelpers.Enums;

namespace DHelpers.ExtensionsHelper
{
    public static class FileHelper
    {
        /// <summary>
        /// Tem curent user folder get.
        /// </summary>
        /// <typeparam name="T">object.</typeparam>
        /// <returns>Path.</returns>
        private static string GetObjectDir<T>()
        {
            var location = Path.GetTempPath();
            var name = typeof(T).Name;
            if (!Directory.Exists(string.Format("{0}\\Saves_01a\\", location)))
            {
                Directory.CreateDirectory(string.Format("{0}\\Saves_01a\\", location));
            }
            return string.Format("{0}\\Saves_01a\\{1}.obj", location, name);
        }

        /// <summary>
        /// Serialize and save object.
        /// </summary>
        /// <typeparam name="T">object</typeparam>
        /// <param name="obj">object</param>
        /// <param name="typeFile">Type of save</param>
        public static void SaveObject<T>(this T obj, FileTypes typeFile = FileTypes.Xml) where T : class
        {
            var serializer = new XmlSerializer(typeof(T));
            using (var fs = new FileStream(GetObjectDir<T>(), FileMode.OpenOrCreate))
            {
                serializer.Serialize(fs, obj);
                fs.Flush();
            }
        }

        /// <summary>
        /// Read and save object
        /// </summary>
        /// <typeparam name="T">object</typeparam>
        /// <param name="obj">object</param>
        /// <param name="typeFile">Type of read</param>
        /// <returns></returns>
        public static T LoadObject<T>(this T obj, FileTypes typeFile = FileTypes.Xml) where T : class
        {
            try
            {
                var serializer = new XmlSerializer(typeof(T));
                using (var fs = new FileStream(GetObjectDir<T>(), FileMode.Open))
                {
                    return (T)serializer.Deserialize(fs);
                }
            }
            catch { return null; }
        }

        public static void DeleteObject<T>(this T obj)
        {
            var path = GetObjectDir<T>();
            if (File.Exists(path)) { File.Delete(path); }
        }
    }
}